<?php

namespace app\admin\controller\wanlshop;

use WanlPay\Yansongda\Pay;
use addons\wanlshop\library\WanlPay\WanlPay;
use app\admin\model\UserIntroduce;
use app\api\model\wanlshop\WithdrawalCash;
use app\common\controller\Backend;
use app\common\model\User;
use app\common\model\UserFinanceLog;
use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{

    /**
     * Withdraw模型对象
     * @var \app\admin\model\wanlshop\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Withdraw;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 首页
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user' => function ($query) {
                    $query->withField('id,nickname');
                }, 'cash'
                ])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)->each(function ($item) {
                    $item->withdraw_type = WithdrawalCash::$wType[$item->cash->type] ?? '';
                });

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->with(['cash', 'user' => function ($query) {
            $query->withField('id,nickname,mobile');
        }])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 同意
     */
    public function agree($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['status'] == 'successed') {
            $this->error(__('已审核过，请不要重复审核！'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }

                //1-商品旧物提现(换购)，2-余额提现，3-活动提现 4-转介绍
                //todo 由平台工作人员充到客户银行卡/微信/支付宝
                /*$user = User::find($row->user_id);
                $cash = WithdrawalCash::where('w_id', $ids)->find();
                if ($cash) {
                    switch ($cash->type) {
                        case 1:
                            break;
                        case 2:
                            //TODO 余额提现，对接支付系统
                            break;
                        case 3:
                            break;
                        case 4:
                            $userIntroduce = UserIntroduce::where('uid', $row->user_id)->find();
                            if ($userIntroduce) {
                                $userIntroduce->withdrawing = bcsub($userIntroduce->withdrawing, $row->money, 2);
                                $userIntroduce->withdrawed = bcadd($userIntroduce->withdrawed, $row->money, 2);
                                $userIntroduce->save();
                            }
                            break;
                    }

                    //1-商品旧物提现(换购)，2-余额提现，3-活动提现 4-转介绍
                    $before = in_array($cash->type, [1, 3, 4]) ? $user->money : bcadd($user->money, $row->money, 2);
                    $after = in_array($cash->type, [1, 3, 4]) ? bcadd($user->money, $row->money, 2) : $user->money;
                    UserFinanceLog::create([
                        'user_id' => $row->user_id,
                        'type' => 'money',
                        'flag' => in_array($cash->type, [1, 3, 4]) ? 'add' : 'reduce',
                        'value' => $row->money,
                        'before' => $before,
                        'after' => $after,
                        'event' => 'withdraw',
                        'status' => 'succeed',
                        'createtime' => time(),
                        'updatetime' => time()
                    ]);
                    if ($cash->type == 2) {//余额提现
                        $user->frozen = bcsub($user->frozen, $row->money, 2);
                        //todo 打款流程
                        $res = $this->withdrawHandle($cash->id);
                        var_dump($res);
                    } else {
                        $user->money = $after;
                    }
                    $user->save();
                }*/

                // 审核通过
                $result = $row->allowField(true)->save([
                    'status' => 'successed',
                    'transfertime' => time()
                ]);

                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 拒绝
     */
    public function refuse($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['status'] = 'rejected';
                    $result = $row->allowField(true)->save($params);

                    $user = User::find($row->user_id);
                    $cash = WithdrawalCash::where('w_id', $ids)->find();
//                    $wanlPay = new WanlPay();
                    if ($cash->type == 2) {
                        $user->money = bcadd($user->money, $row->money, 2);
                        $user->frozen = bcsub($user->frozen, $row->money, 2);
                        $user->save();
                    }/* else {
                        $wanlPay::money(+bcadd($row['money'], $row['handingfee'], 2), $row['user_id'], '提现失败返回余额', 'withdraw', $row['id']);
                    }*/

                    // 更新用户金额
                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function withdrawHandle($id)
    {
        $cashModel = WithdrawalCash::find($id);
        if (!$cashModel) {
            return '提现1数据不存在';
        }
        if ($cashModel->type != 2) {
            return '非法操作';
        }
        $withdrawModel = \app\admin\model\wanlshop\Withdraw::find($cashModel->w_id);
        if (!$withdrawModel) {
            return '提现2数据不存在';
        }
        if ($withdrawModel->status != 'created') {
            return '提现数据状态错误';
        }
        switch ($cashModel->channel) {
            case 1://银行卡
                break;
            case 2://微信
                break;
            case 3://支付宝
                $res = (new WanlPay('alipay', 'transfer'))->transfer($cashModel->id, $cashModel->amount, $cashModel->alipay_account, $cashModel->truename);
                return $res;
                break;
        }
        return true;
    }
}
